<?php
/**
 * XImageServer
 * fetch image and save,when no image in this site
 * @author xiongchuan <xiongchuan86@gmail.com>
 */
class FetchImage{
    static private $_size;
    static private $_imageUrl;
    static private $_imageExt;
    static private $_path;
    //定义需要映射的图片物理路径
    static private $_config = array(
        'music'    => '/var/static/img/music',
        'avatar'  => '/var/static/img/avatar',
    );
    //定义允许的图片格式
    static private $_ext = array('jpg','jpeg','gif','png');
    //定义图片格式对应的处理函数
    static private $_imageMethod=  array(
        'jpg'  => 'imagejpeg',
        'jpeg' => 'imagejpeg',
        'gif'  => 'imagegif',
        'png'  => 'imagepng',
    );
    //定义各模块允许的图片尺寸
    static private $_allowedSize = array(
        'avatar'=>array('30x30','50x50','80x80','150x150','180x180'),
    );

    static private $_curKey;

    //入口
    static public function fetch(){
        self::parse();
        self::copyImage();
    }

    //分析url
    static private function parse(){
        //重定向过来的URL 支持Apache和Nginx 当二次开发时，此处可修改为你需要的URL
        $query = isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : $_SERVER['REQUEST_URI'];
        //用/分隔url
        $tmp = explode("/",$query);
        //判断是否为合法的图片路径
        if(preg_match('/\.(jpg|jpeg|png|gif)$/i',$query,$m)){
            $ext = $m[1];
        }else{
            exit;
        }
        empty($tmp[0]) && array_shift($tmp);
        //url_key 应该是music/avatar/...
        $url_key = array_shift($tmp);
        self::$_curKey = $url_key;
        if( count($tmp)>1 && isset(self::$_config[$url_key]) && in_array(strtolower($ext), self::$_ext)){
            self::$_imageExt = strtolower($ext);
            self::$_imageUrl = self::$_config[$url_key].'/'.join("/",$tmp);
            //echo self::$_imageUrl;exit;
            if(preg_match('/\/(\d*x\d*)\//i', self::$_imageUrl,$m)){
                self::$_size = $m[1];
                if(in_array(self::$_curKey, self::$_allowedSize)){
                    if(!in_array(self::$_size, self::$_allowedSize[self::$_curKey])){
                        exit;
                    }
                }
                //echo self::$_size;exit;
                //把网址中的尺寸替换为origin 去取真实的图片
                self::$_imageUrl = str_replace(self::$_size, 'origin', self::$_imageUrl);
                //echo self::$_imageUrl;exit;
            }
            self::$_path     = dirname(__FILE__)."/../".str_replace(basename($query),"" , $query);
        }else{
            exit;
        }
    }

    /**
     * 把图片从网络文件系统(NFS)中复制到当前网站目录下，并按尺寸压缩
     */
    static private function copyImage(){
        if(!is_file(self::$_imageUrl)){
            self::defaultImage();
        }
        $image = imagecreatefromstring(file_get_contents(self::$_imageUrl));
        $filename = self::$_path.basename(self::$_imageUrl);
        if($image){
            header('Content-Type:image/'.self::$_imageExt);
            $method = self::$_imageMethod[self::$_imageExt];
            if(!empty(self::$_size)){
                self::$_path = str_replace(self::$_size,'origin', self::$_path);
                self::mkdirs();
                $filename = str_replace(self::$_size, 'origin', $filename);
                $method($image,$filename);
                //thumb
                $size = explode("x",self::$_size);
                $thumb = imagecreatetruecolor($size[0], $size[1]);
                self::$_path = str_replace('origin',self::$_size, self::$_path);
                self::mkdirs();
                list($width, $height) = getimagesize($filename);
                $filename = str_replace('origin', self::$_size,$filename);
                imagecopyresampled($thumb, $image, 0, 0, 0, 0, $size[0], $size[1], $width, $height);
                $method($thumb);
                $method($thumb,$filename);
            }
            //
            else if($method($image) && self::mkdirs()){
                $method($image,$filename);
            }
        }
    }
    
    //递归创建目录
    static private function mkdirs(){
        if(!is_dir(self::$_path)){
            return mkdir(self::$_path,0700,true);
        }
        return true;
    }

    //当前指定的图片不存在时，读取默认图片
    static private function defaultImage(){
        $filename = self::$_curKey . "_" . self::$_size . ".jpg";
        $defaultImage = "/default/" . $filename;
        header("location:".$defaultImage);
        exit;
    }

}